<template>

  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>
<script>
import COS from 'cos-js-sdk-v5'
/*
  action 上传方式 - 携带地址 - 自动上传
  手动上传 腾讯云服务器

  before-upload 上传之前的检查
*/
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {

    }
  },
  methods: {
    uploadImage(params) {
      console.log(params)
      const cos = new COS({
        SecretId: 'AKIDpUu4yc080BZQ2OVMyLSM1QaVigOr66qM', // 应用标识
        SecretKey: 'LQGyY8TYO5XjgOs64miPq2zh9MJ0RdZ0' // 应用秘钥
      })
      cos.putObject({
        Bucket: 'hmhr-111-1257341766', // 存储桶的名称
        Region: 'ap-nanjing', // 地域
        Key: params.file.name, // 文件名称
        StorageClass: 'STANDARD', // 标准
        Body: params.file // 文件对象
      }, (err, data) => {
        if (data.statusCode === 200 && data.Location) {
          this.$emit('input', 'https://' + data.Location)
        } else {
          this.$message.error(err.message)
        }
      })
    },
    // 上传文件时 - 钩子函数 (检查图片的类型及大小)
    beforeAvatarUpload(file) {
      //  jpeg png gif bmp
      // 限制图片的类型
      const typeList = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
      const isJPG = typeList.includes(file.type)
      // b -> kb -> M
      // 限制图片的大小
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片的格式不符合要求!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
